package com.hrb.douban.activtity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hrb.commonsdk.okhttp.listener.DisposeDataListener;
import com.hrb.commonsdk.okhttp.request.RequestParams;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.R;
import com.hrb.douban.activtity.base.BaseActivity;
import com.hrb.douban.constant.ConstantCode;
import com.hrb.douban.constant.HttpConstants;
import com.hrb.douban.mview.CollectBtn;
import com.hrb.douban.network.RequestCenter;
import com.hrb.douban.record.PersonRecord;
import com.hrb.douban.utils.ACache;
import com.hrb.douban.utils.DateUtil;
import com.hrb.douban.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Iterator;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class PersonDetailActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.person_avatar_title)
    TextView personAvatarTitle;
    @BindView(R.id.person_detail_back_icons)
    ImageView personDetailBackIcons;
    @BindView(R.id.person_avatar)
    CircleImageView personAvatar;
    @BindView(R.id.person_name)
    TextView personName;
    @BindView(R.id.person_name_en)
    TextView personNameEn;
    @BindView(R.id.person_address)
    TextView personAddress;
    @BindView(R.id.person_works)
    GridLayout personWorks;
    @BindView(R.id.collect_button)
    CollectBtn collectButton;
    private PersonRecord record;
    private ACache cacheUtil;
    private ArrayList<PersonRecord> personlist = new ArrayList<PersonRecord>();
    private ArrayList<PersonRecord> collectlist = new ArrayList<PersonRecord>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_detail);
        ButterKnife.bind(this);
        personDetailBackIcons.setOnClickListener(this);
        requestData(null, getIntent().getStringExtra("id"));
        cacheUtil = ACache.get(CustomApplication.getContext());
    }

    private void requestData(RequestParams params, String id) {
        RequestCenter.getRequest(HttpConstants.CELEBRITYROOT + id, params, PersonRecord.class, new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                if (responseObj != null) {
                    record = (PersonRecord) responseObj;
                    if ((ArrayList<PersonRecord>) cacheUtil.getAsObject("personlist") != null) {
                        personlist = (ArrayList<PersonRecord>) cacheUtil.getAsObject("personlist");
                    }
                    record.setAddTime(DateUtil.getDate());
                    Iterator<PersonRecord> iterator = personlist.iterator();
                    while (iterator.hasNext()) {
                        PersonRecord p = iterator.next();
                        if (record != null && record.getId() != null && record.getId().equals(p.getId())) {
                            iterator.remove();
                        }
                    }
                    personlist.add(0,record);
                    cacheUtil.put("personlist", personlist, 1000 * 60);
                    Glide.with(CustomApplication.getContext()).load(record.getAvatars().getMedium()).centerCrop().into(personAvatar);
                    personName.setText(record.getName());
                    personAvatarTitle.setText(record.getName());
                    personNameEn.setText(record.getName_en());
                    personAddress.setText(record.getBorn_place());
                    for (PersonRecord.WorksBean worksBean : record.getWorks()) {
                        View itemView = (View) LayoutInflater.from(CustomApplication.getContext()).inflate(R.layout.person_work_item, personWorks, false);
                        ImageView imageView = itemView.findViewById(R.id.item_work_img);
                        TextView nameText = itemView.findViewById(R.id.item_work_name);
                        TextView roleText = itemView.findViewById(R.id.item_work_role);
                        Glide.with(CustomApplication.getContext()).load(worksBean.getSubject().getImages().getMedium()).centerCrop().into(imageView);
                        nameText.setText(worksBean.getSubject().getTitle());
                        String roleStr = worksBean.getRoles().toString();
                        roleStr = roleStr.substring(1, roleStr.lastIndexOf("]"));
                        roleText.setText("担任 : " + roleStr);
                        final String workId = worksBean.getSubject().getId();
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getApplicationContext(), FilmDetailsActivity.class);
                                intent.putExtra("id", workId);
                                startActivityForResult(intent, ConstantCode.requestCode);
                            }
                        });
                        personWorks.addView(itemView);
                        initCollectState();
                    }
                }

            }

            @Override
            public void onFailure(Object reasonObj) {

            }
        });
    }

    private void initCollectState() {
        //初始化
        if ((ArrayList<PersonRecord>) cacheUtil.getAsObject("personlistCollect") != null) {
            collectlist = (ArrayList<PersonRecord>) cacheUtil.getAsObject("personlistCollect");
        }
//        收藏列表是否有此记录
        Iterator<PersonRecord> iterator = collectlist.iterator();
        while (iterator.hasNext()) {
            PersonRecord p = iterator.next();
            if (record != null && record.getId() != null && record.getId().equals(p.getId())) {
                collectButton.setmState(true);
            }
        }
        collectButton.setmCollectBtnChangeListener(new CollectBtn.CollectBtnChangeListener() {
            @Override
            public void onClick(boolean flag) {
                ToastUtil.show(flag ? "已收藏" : "取消收藏");
                if ((ArrayList<PersonRecord>) cacheUtil.getAsObject("personlistCollect") != null) {
                    collectlist = (ArrayList<PersonRecord>) cacheUtil.getAsObject("personlistCollect");
                }
                if (flag) {
                    record.setAddTime(DateUtil.getDate());
                    Iterator<PersonRecord> iterator = collectlist.iterator();
                    while (iterator.hasNext()) {
                        PersonRecord p = iterator.next();
                        if (record != null && record.getId() != null && record.getId().equals(p.getId())) {
                            iterator.remove();
                        }
                    }
                    collectlist.add(0, record);
                    cacheUtil.put("personlistCollect", collectlist, 1000 * 60);
                } else {
                    Iterator<PersonRecord> iterator = collectlist.iterator();
                    while (iterator.hasNext()) {
                        PersonRecord p = iterator.next();
                        if (record != null && record.getId() != null && record.getId().equals(p.getId())) {
                            iterator.remove();
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.person_detail_back_icons:
                /*Intent backIntent = new Intent(this, MainActivity.class);
                backIntent.putExtra("name", 1);
                PersonDetailActivity.this.setResult(ConstantCode.resultCode, backIntent);
                //startActivity(backIntent);
                */
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /*Intent backIntent = new Intent(this, MainActivity.class);
            backIntent.putExtra("name", 1);
            PersonDetailActivity.this.setResult(ConstantCode.resultCode, backIntent);*/
            finish();

        }
        return true;

    }
}
